package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.IotMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 设备数据Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-25
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 查询设备数据列表
     *
     * @param dto@return 设备数据集合
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        List<DeviceData> list = this.lambdaQuery().eq(StrUtil.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StrUtil.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .eq(StrUtil.isNotBlank(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .list();
        return list;
    }

    @Autowired
    private IDeviceService deviceService;

    /**
     * 基于IOT设备上传通知的数据，批量保存设备数据
     *
     * @param iotMsgNotifyData
     */
    @Transactional
    @Override
    public void saveBatchData(IotMsgNotifyData iotMsgNotifyData) {

        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        //判断设备是否存在
        Device device = deviceService.lambdaQuery().eq(Device::getIotId,deviceId).one();
        if(device==null){
            log.error("设备不存在，iotId：{}", deviceId );
            return;
        }

        //构建设备数据（可能存在多态设备数据，所以要遍历构建）
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        List<DeviceData> deviceDataList = new ArrayList<>();
        services.forEach(s->{
            String eventTimeStr = s.getEventTime();
            LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            s.getProperties().forEach((k,v)->{
                DeviceData deviceData = DeviceData.builder()
                        .iotId(deviceId)
                        .functionId(k)//功能名（设备上报属性名）
                        .dataValue(v.toString()) //数据值（设备上报属性值）
                        .alarmTime(eventTime)//数据上报时间
                        .locationType(device.getLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .deviceName(device.getDeviceName())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .nickname(device.getNickname())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .build();
                deviceDataList.add(deviceData);
            });
        });

        //批量保存设备数据
        if(CollUtil.isNotEmpty(deviceDataList)){
            boolean result = saveBatch(deviceDataList);
            log.info("[批量保存上报的设备数据]结果：{}", result);
        }
        //将最新的数据保存到redis中
        redisTemplate.opsForHash().put(CacheConstants.DEVICE_DATA_NEW, device.getIotId(), JSONUtil.toJsonStr(deviceDataList));

    }
}
